package org.timemachine.listener;

import javax.persistence.PersistenceException;
import javax.persistence.PostPersist;
import javax.persistence.PrePersist;

import org.timemachine.action.facade.EntityChangeFacade;
import org.timemachine.action.facade.ForwardEntityChangeFacade;
import org.timemachine.context.TMScheduleThreadLocal;
import org.timemachine.context.TMThreadLocal;
import org.timemachine.factory.EntityChangeFactory;
import org.timemachine.factory.spi.EntityChange;

public class TimeMachineInsertListener extends TimeMachineBaseListener {

	@PostPersist
	public void postPersist(Object entity) throws Exception {

		if (!TMScheduleThreadLocal.get().isSchedule() && isEntityHasChangeAnno(entity)) {

			EntityChange entityChange = getEntityChangeForEntity(entity);
			EntityChangeFactory.copyProperties(entityChange, entity);
			entityChange.setChangeType(EntityChangeFactory.CHANGE_TYPE_INSERT);

			EntityChangeFacade entityChangeFacade = findEntityChangeFacade();
			entityChangeFacade.createEntityChange(entityChange);

		}
		TMScheduleThreadLocal.unset();
	}

	@PrePersist
	public void prePersist(Object entity) throws Exception {

		if (TMThreadLocal.getContext().isLaterDate()
				&& !TMScheduleThreadLocal.get().isSchedule()
				&& isEntityHasChangeAnno(entity)) {

			EntityChange entityChange = getEntityChangeForEntity(entity);
			EntityChangeFactory.copyProperties(entityChange, entity);
			entityChange.setChangeType(EntityChangeFactory.CHANGE_TYPE_INSERT);

			ForwardEntityChangeFacade forwardEntityChangeFacade = findForwardEntityChangeFacade();
			forwardEntityChangeFacade.createForwardEntityChange(entityChange);
			TMThreadLocal.unset();
			throw new PersistenceException("TimeMachine : save forward entity, exception for normal transaction application entity.");
		}

	}

}
